package cn.harry.modular.cp.service.impl;

import cn.harry.modular.cp.vo.EvaluationUserLoginCodeVO;
import cn.harry.modular.system.service.SysUserService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.harry.modular.cp.mapper.EvaluationUserMapper;
import cn.harry.modular.cp.service.EvaluationUserService;
import cn.harry.modular.cp.domain.EvaluationUser;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import org.springframework.transaction.annotation.Transactional;

/**
 * 评测服务实现类
 *
 * @author harry
 * @公众号 Harry技术
 */
@Service
@RequiredArgsConstructor
public class EvaluationUserServiceImpl extends ServiceImpl<EvaluationUserMapper, EvaluationUser> implements EvaluationUserService {
    private final SysUserService sysUserService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importSave(Long evaluationId, List<EvaluationUser> list) {
        list.forEach(item -> {
//            随机生成8位数字，不重复
            item.setLoginCode(IdUtil.nanoId(8));
            // 设置评测id
            item.setEvaluationId(evaluationId);
        });
        // 生成登录码，对应user
        List<String> loginCodes = list.stream().map(EvaluationUser::getLoginCode).toList();
        sysUserService.genUserByLoginCode(loginCodes);
        // 批量插入
        return saveBatch(list);
    }

    @Override
    public List<EvaluationUserLoginCodeVO> getLoginCode(Long evaluationId) {
        List<EvaluationUser> list = baseMapper.selectList(Wrappers.<EvaluationUser>lambdaQuery()
                .eq(EvaluationUser::getEvaluationId, evaluationId));
        if (!list.isEmpty()) {
            return BeanUtil.copyToList(list, EvaluationUserLoginCodeVO.class);
        }
        return null;
    }

    @Override
    public EvaluationUser getUserByLoginCode(String loginCode) {
        return getOne(Wrappers.<EvaluationUser>lambdaQuery().eq(EvaluationUser::getLoginCode, loginCode));
    }


    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(IdUtil.nanoId(6).toUpperCase());
        }
    }
}
